package java_thread.demo02;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

//线程创建方式三：实现callcable 方式

//calable的优点
//1. 可以定义返回值
// 2. 可以抛出异常
public class TestCallable implements Callable<Boolean> {
    private  String url;  //网络图片的地址
    private  String name; // 网络图片的名称

    public TestCallable (String url,String name){
        this.name = name;
        this.url = url;
    }
    // 线程的执行体
    @Override
    public Boolean call() {
        WebDownLoader webDownLoader =  new WebDownLoader();
        webDownLoader.download(url,name);
        System.out.println("下载了文件名为："+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable("https://www.westos.org/img/pic-1.png","1.jpg");
        TestCallable t2 = new TestCallable("https://www.westos.org/img/pic-2.png","2.jpg");
        TestCallable t3 = new TestCallable("https://www.westos.org/img/pic-3.png","3.jpg");
        // 创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(1);
        // 提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);

        // 获取结果
        boolean rs1 = r1.get();
        boolean rs2 = r2.get();
        boolean rs3 = r3.get();

        System.out.println(rs1);
        System.out.println(rs2);
        System.out.println(rs3);



        //  关闭服务
        ser.shutdownNow();


    }

}


// 下载器
class  WebDownLoader{
    //下载方法
    public static void download(String url,String name) {
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常，downloader 方法出现问题");
        }
    }
}